package com.binc.testspring.study.nio.netty.simple;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * FileName: My_client_handler   自定义的客户端handler     继承netty的ChannelInboundHandlerAdapter
 *      需要继承netty 规定好的某个HandlerAdapter(规范), 这时我们自定义一个Handler , 才能称为一个handler
 * Autho: binC
 * Date:  2022/4/19 14:49
 */
@Slf4j
public class My_client_handler extends ChannelInboundHandlerAdapter {


    //当通道就绪就会触发该方法   即:客户端的通到好了之后,我们这里就触发发送消息了
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("-----lient " + ctx);
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, server: (>^ω^<)喵", CharsetUtil.UTF_8));
    }


    //当通道有读取事件时，会触发
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        ByteBuf buf = (ByteBuf) msg;
        log.info("----->>>>> 服务端回复的消息是:{}",buf.toString(CharsetUtil.UTF_8));
        log.info("----->>>>> 服务端的地址是{}",ctx.channel().remoteAddress());
        log.info("----------------------------------------------------------------");

    }

    /**
     *发生异常的话,关闭通道
     * @param ctx
     * @param cause
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // super.exceptionCaught(ctx, cause);
        cause.printStackTrace();
        ctx.close();
    }
}
